﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Blog.IService;
using Blog.ServiceContainer;
using Blog.Model;
using Blog.Util;
using System.Data.SqlClient;
using System.Text;
using System.Data;
using Dapper;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Caching.Distributed;
using Blog.WebApp;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using System.IO;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Cors;
using System.Net.Mail;

namespace WebApp.Controllers
{
    [EnableCors("any")]
    public class HomeController : Controller
    {
        HttpClient client = new HttpClient();
        private DistributedCache _Cache;
        /// <summary>
        ///   构造注入
        /// </summary>
        /// <param name="Cache"></param>
        public HomeController(IDistributedCache Cache)
        {
            _Cache = new DistributedCache(Cache);
        }
        public static string conStr = "server=.;uid=sa;pwd=123456;database=Helper";
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        #region 登录
        public ActionResult Login()
        {
            return View();
        }
        [Obsolete]
        public async Task<IActionResult> checkLoginAsync(Admin admin)
        {
            IAdminService AS = Container.Resolve<IAdminService>();
            var Admin = AS.GetModel(a => a.AdminName == admin.AdminName && a.AdminPwd == admin.AdminPwd).FirstOrDefault();
            bool result = Admin != null;
            if (result)
            {
                //登陆授权
                var claims = new List<Claim>();

                claims.Add(new Claim(ClaimTypes.Name, Admin.AdminName));
                claims.Add(new Claim("id", Admin.Adminid.ToString()));
                var indentity = new ClaimsIdentity(claims, "denglu");

                var principal = new ClaimsPrincipal(indentity);

                await HttpContext.SignInAsync(

                  CookieAuthenticationDefaults.AuthenticationScheme,

                  principal);

                //验证是否授权成功

                if (principal.Identity.IsAuthenticated)
                {
                    return Json("Index");
                }
                return Json("");
            }
            else
            {
                return Json("0");
            }

        }

        public async Task<IActionResult> OnGetLoginOutAsync()
        {
            _Cache.Remove("zmk"); _Cache.Remove("lm"); _Cache.Remove("wz");
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            IParentService ps = Container.Resolve<IParentService>();
            ICategoryService cs = Container.Resolve<ICategoryService>();
            IArticleService articleService = Container.Resolve<IArticleService>();

            //主模块
            _Cache.Add("zmk", JsonConvert.SerializeObject(ps.GetModel(a => true).ToList()));
            //var obj= _Cache.Get("zmk");
            //栏目
            _Cache.Add("lm", JsonConvert.SerializeObject(cs.GetModel(a => true).ToList()));
            //文章
            _Cache.Add("wz", JsonConvert.SerializeObject(articleService.GetModel(a => true).ToList()));
            return Json("Login");
        }

        #endregion

        #region
        public ActionResult Register()
        {
            return View();
        }
        #endregion
        #region 主模块管理
        [Authorize]
        public ActionResult Parent()
        {
            return View();
        }
        [Authorize]
        public ActionResult EditParent()
        {

            return View();
        }
        [Authorize]
        public ActionResult UpdateParent()
        {
            return View();
        }
        public JsonResult parenttable()
        {
            IParentService ps = Container.Resolve<IParentService>();
            var list = ps.GetModel(a => true).Select(a => new { id = a.Parentid, Pname = a.Pname }).ToList();
            return Json(list);
        }
        public JsonResult addparent(Parent parent)
        {
            _Cache.Remove("zmk");
            IParentService ps = Container.Resolve<IParentService>();
            bool result = ps.Add(parent);
            string str = "";
            if (result)
                str = Message.Success_Add;
            else
                str = Message.Error_Add;
            _Cache.Add("zmk", JsonConvert.SerializeObject(ps.GetModel(a => true).ToList()));
            return Json(str);
        }
        public JsonResult deleteparent(string[] no)
        {
            _Cache.Remove("zmk");
            IParentService ps = Container.Resolve<IParentService>();
            string str = "";
            try
            {
                foreach (var id in no)
                {
                    Parent p = new Blog.Model.Parent();
                    p.Parentid = int.Parse(id);
                    bool result = ps.Delete(p);
                }

                str = Message.Success_Delete;
            }
            catch (Exception ex)
            {
                str = Message.Error_Delete;
            }
            _Cache.Add("zmk", JsonConvert.SerializeObject(ps.GetModel(a => true).ToList()));
            return Json(str);
        }
        public JsonResult update_parent(Parent parent)
        {
            _Cache.Remove("zmk");
            IParentService ps = Container.Resolve<IParentService>();
            string str = "";
            try
            {
                ps.Update(parent);
                str = Message.Success_Edit;
            }
            catch (Exception ex)
            {
                str = Message.Error_Edit;
            }
            _Cache.Add("zmk", JsonConvert.SerializeObject(ps.GetModel(a => true).ToList()));
            return Json(str);
        }
        #endregion

        #region 栏目管理
        [Authorize]
        public ActionResult Category()
        {
            return View();
        }
        [Authorize]
        public ActionResult EditCategory()
        {
            return View();
        }
        [Authorize]
        public ActionResult UpdateCategory()
        {
            return View();
        }
        public JsonResult categorytable(int rows, int page, int Parentid)
        {
            using (IDbConnection db = new SqlConnection(conStr))
            {
                StringBuilder str = new StringBuilder();
                str.Append(@"Select *From Parent p join Category c on p.Parentid=c.Parentid ");
                try
                {
                    var list = db.Query<Parent, Category, Parent>(str.ToString(), (p, c) => { p.category = c; return p; }, null, null, true, "CategoryId");
                    if (Parentid != 0)
                    {
                        str.Append("Where c.Parentid=@Parentid");
                        list = db.Query<Parent, Category, Parent>(str.ToString(), (p, c) => { p.category = c; return p; }, new { Parentid = Parentid }, null, true, "CategoryId");
                    }
                    var list1 = list.Skip(rows * (page - 1)).Take(rows).Select(a => new { id = a.category.CategoryId, Cname = a.category.Cname, Pname = a.Pname });
                    var pageUI = new { total = list.ToList().Count, rows = list1.ToList() };

                    return Json(pageUI);
                }
                catch (Exception ex)
                {
                    return Json("");
                }
            }
        }
        public JsonResult deletecategory(string[] no)
        {
            _Cache.Remove("lm");
            ICategoryService ps = Container.Resolve<ICategoryService>();
            string str = "";
            try
            {
                foreach (var id in no)
                {
                    Category p = new Blog.Model.Category();
                    p.CategoryId = int.Parse(id);
                    bool result = ps.Delete(p);
                }
                str = Message.Success_Delete;
            }
            catch (Exception ex)
            {
                str = Message.Error_Delete;
            }
            _Cache.Add("lm", JsonConvert.SerializeObject(ps.GetModel(a => true).ToList()));
            return Json(str);
        }
        public JsonResult addcategory(Category cate)
        {
            _Cache.Remove("lm");
            ICategoryService cs = Container.Resolve<ICategoryService>();
            bool result = cs.Add(cate);
            string str = "";
            if (result)
                str = Message.Success_Add;
            else
                str = Message.Error_Add;
            _Cache.Add("lm", JsonConvert.SerializeObject(cs.GetModel(a => true).ToList()));
            return Json(str);
        }
        public JsonResult edit_Category(Category cate)
        {
            _Cache.Remove("lm");
            ICategoryService cs = Container.Resolve<ICategoryService>();
            string str = "";
            try
            {
                cs.Update(cate);
                str = Message.Success_Edit;
            }
            catch (Exception)
            {
                str = Message.Error_Edit;
            }
            _Cache.Add("lm", JsonConvert.SerializeObject(cs.GetModel(a => true).ToList()));
            return Json(str);
        }
        #endregion

        #region 文章管理
        [Authorize]
        public ActionResult Article()
        {

            return View();
        }
        [Authorize]
        public ActionResult EditArticle()
        {
            IParentService ps = Container.Resolve<IParentService>();
            var list = ps.GetModel(a => true).ToList();
            ViewData["ParentSel"] = list;
            var no = Request.QueryString.Value.Replace("?id=", "");
            if (no == null || no == "")
            {
                Article a = new Article();
                a.CommentStatus = "";
                a.Recommend = "";
                return View(a);
            }
            else
            {
                int id = int.Parse(no);
                IArticleService articleService = Container.Resolve<IArticleService>();
                return View(articleService.GetModel(a => a.Articleid == id).FirstOrDefault());
            }
        }

        public JsonResult articletable(int rows, int page, string title)
        {
            if (title == null) { title = ""; }
            using (IDbConnection db = new SqlConnection(conStr))
            {
                StringBuilder str = new StringBuilder();
                str.Append(@"Select *From Article ar join Admin ad on ar.Adminid=ad.Adminid join Category c on ar.CategoryId=c.CategoryId");
                try
                {
                    var list = db.Query<Article, Admin, Category, Article>(str.ToString(), (ar, ad, c) => { ar.admin = ad; ar.category = c; return ar; }, null, null, true, "Articleid,Adminid,CategoryId");
                    var list1 = list.Where(a => a.Title.Contains(title)).Select(a => new { id = a.Articleid, Recommend = a.Recommend, CommentStatus = a.CommentStatus, Title = a.Title, Cname = a.category.Cname, AdminName = a.admin.AdminName }).ToList();
                    var table = list1.Skip(rows * (page - 1)).Take(rows).ToList();
                    var pageUI = new { total = list.ToList().Count, rows = table.ToList() };

                    return Json(pageUI);
                }
                catch (Exception ex)
                {
                    return Json("");
                }
            }
        }
        public JsonResult CategorySel(int no)
        {
            ICategoryService cs = Container.Resolve<ICategoryService>();
            var list = cs.GetModel(a => a.Parentid == no).ToList();
            return Json(list);
        }
        public JsonResult addarticle(Article article)
        {
            _Cache.Remove("wz");
            if (article.CommentStatus == null) { article.CommentStatus = ""; }
            if (article.Recommend == null) { article.Recommend = ""; }
            IArticleService AS = Container.Resolve<IArticleService>();
            string str = "";
            try
            {
                IAttentService attentService = Container.Resolve<IAttentService>();
                List<UserInfo> userInfos = JsonConvert.DeserializeObject<List<UserInfo>>(_Cache.Get("User").ToString());
                List<Attent> attents = attentService.GetModel(a => a.CategoryId == article.CategoryId);
                article.ReleaseDate = DateTime.Now;
                AS.Add(article);
                foreach (var item in attents)
                {
                    UserInfo userInfo = userInfos.Where(a => a.Userid == item.Userid).FirstOrDefault();
                    MailAddress MessageFrom = new MailAddress("wufan19980120@163.com"); //发件人邮箱地址
                    string MessageTo = userInfo.Email; //收件人邮箱地址
                    string MessageSubject = article.Title; //邮件主题
                    string MessageBody = "这是链接";//邮箱内容
                    EmailRegister.Send(MessageFrom, MessageTo, MessageSubject, MessageBody);
                }
                str = Message.Success_Add;
            }
            catch (Exception ex)
            {
                str = Message.Error_Add;
            }
            _Cache.Add("wz", JsonConvert.SerializeObject(AS.GetModel(a => true).ToList()));
            return Json(str);
        }
        public JsonResult deletearticle(string[] no)
        {
            _Cache.Remove("wz");
            IArticleService ps = Container.Resolve<IArticleService>();
            string str = "";
            try
            {
                foreach (var id in no)
                {
                    Article p = new Blog.Model.Article();
                    p.Articleid = int.Parse(id);
                    bool result = ps.Delete(p);
                }
                str = Message.Success_Delete;
            }
            catch (Exception ex)
            {
                str = Message.Error_Delete;
            }
            _Cache.Add("wz", JsonConvert.SerializeObject(ps.GetModel(a => true).ToList()));
            return Json(str);
        }
        public JsonResult updatearticle(Article article)
        {
            _Cache.Remove("wz");
            IArticleService AS = Container.Resolve<IArticleService>();
            string str = "";
            if (article.CommentStatus == null) { article.CommentStatus = ""; }
            if (article.Recommend == null) { article.Recommend = ""; }
            try
            {
                article.UpdateDate = DateTime.Now;
                AS.Update(article);
                str = Message.Success_Edit;
            }
            catch (Exception ex)
            {
                str = Message.Error_Edit;
            }
            _Cache.Add("wz", JsonConvert.SerializeObject(AS.GetModel(a => true).ToList()));
            return Json(str);
        }
        #endregion

        #region 评论管理
        public ActionResult Comment()
        {
            return View();
        }
        public JsonResult CommentTable(int rows, int page, string name)
        {
            if (name == null) { name = ""; }
            using (IDbConnection db = new SqlConnection(conStr))
            {
                StringBuilder str = new StringBuilder();
                str.Append(@"Select *From Article a join Comment c on a.Articleid=c.Articleid");
                try
                {
                    var user = db.Query("Select*From UserInfo").ToList();
                    var comment = db.Query<Article, Comment, Article>(str.ToString(), (a, c) => { a.comment = c; return a; }, null, null, true, "Commentid")
                        .Select(a => new { Title = a.Title, Articleid = a.Articleid, id = a.comment.Commentid, Userid = a.comment.Userid, Content = a.comment.Content, CommDate = a.comment.CommDate });
                    var list = user.Join(comment, a => a.Userid, b => b.Userid, (x, y) => new { x, y })
                        .Where(a => a.y.Title.Contains(name))
                        .Select(a => new { Userid = a.x.Userid, Uname = a.x.Uname, Articleid = a.y.Articleid, id = a.y.id, Title = a.y.Title, CommDate = a.y.CommDate, Content = a.y.Content }).ToList();
                    var list1 = list.Where(a => a.Title.Contains(name));
                    var table = list1.Skip(rows * (page - 1)).Take(rows).ToList();
                    var pageUI = new { total = comment.ToList().Count, rows = table.ToList() };

                    return Json(pageUI);
                }
                catch (Exception ex)
                {
                    return Json("");
                }
            }
        }

        public JsonResult DeleteCom(string[] no)
        {
            _Cache.Remove("Comment");
            ICommentService ps = Container.Resolve<ICommentService>();
            string str = "";
            try
            {
                foreach (var id in no)
                {
                    Comment p = new Blog.Model.Comment();
                    p.Commentid = int.Parse(id);
                    bool result = ps.Delete(p);
                }
                str = Message.Success_Delete;
            }
            catch (Exception ex)
            {
                str = Message.Error_Delete;
            }
            _Cache.Add("Comment", JsonConvert.SerializeObject(ps.GetModel(a => true).ToList()));
            return Json(str);
        }
        #endregion

        #region 用户管理
        public ActionResult UserInfo()
        {
            return View();
        }
        public JsonResult UserInfotable()
        {
            IUserInfoService ps = Container.Resolve<IUserInfoService>();
            var list = ps.GetModel(a => true).Select(a => new { id = a.Userid, Uname = a.Uname, Email = a.Email }).ToList();
            return Json(list);
        }
        public ActionResult EditUserInfo(int id)
        {
            IUserInfoService userInfoService = Container.Resolve<IUserInfoService>();
            return View(userInfoService.GetModel(a => a.Userid == id).FirstOrDefault());
        }
        public JsonResult UpdateUserInfo(UserInfo userInfo)
        {
            IUserInfoService userInfoService = Container.Resolve<IUserInfoService>();
            try
            {
                userInfoService.Update(userInfo);
                return Json(Message.Success_Edit);
            }
            catch (Exception)
            {
                return Json(Message.Error_Edit);
            }
        }

        public JsonResult DeleteUserInfo(string no)
        {
            IUserInfoService userInfoService = Container.Resolve<IUserInfoService>();
            int id = int.Parse(no);
            try
            {
                UserInfo userInfo = userInfoService.GetModel(a => a.Userid == id).FirstOrDefault();
                userInfoService.Delete(userInfo);
                return Json(Message.Success_Delete);
            }
            catch (Exception)
            {
                return Json(Message.Error_Delete);
            }
        }
        #endregion

        #region 管理员管理
        public ActionResult AdminInfo()
        {
            return View();
        }
        public JsonResult AdminInfotable()
        {
            IAdminService ps = Container.Resolve<IAdminService>();
            var list = ps.GetModel(a => true).Select(a => new { id = a.Adminid, AdminName = a.AdminName }).ToList();
            return Json(list);
        }
        public ActionResult EditAdminInfo(int id)
        {
            IAdminService adminService = Container.Resolve<IAdminService>();
            if (id != 0)
            {
                return View(adminService.GetModel(a => a.Adminid == id).FirstOrDefault());
            }
            else
            {
                return View(new Admin());
            }

        }
        public JsonResult AddUpdateAdmin(Admin admin)
        {
            IAdminService adminService = Container.Resolve<IAdminService>();
            if (admin.Adminid == 0)
            {
                try
                {
                    adminService.Add(admin);
                    return Json(Message.Success_Add);
                }
                catch (Exception)
                {
                    return Json(Message.Error_Add);
                }
            }
            else
            {
                try
                {
                    adminService.Update(admin);
                    return Json(Message.Success_Edit);
                }
                catch (Exception)
                {
                    return Json(Message.Error_Delete);
                }
            }

        }

        public JsonResult DeleteAdminInfo(string no)
        {
            IAdminService adminService = Container.Resolve<IAdminService>();
            int id = int.Parse(no);
            try
            {
                Admin admin = adminService.GetModel(a => a.Adminid == id).FirstOrDefault();
                adminService.Delete(admin);
                return Json(Message.Success_Delete);
            }
            catch (Exception)
            {
                return Json(Message.Error_Delete);
            }
        }
        #endregion

        #region 工单管理
        public ActionResult Work()
        {
            return View();
        }
        public JsonResult WorkTable(int rows, int page)
        {
            IWorkOrderService workOrderService = Container.Resolve<IWorkOrderService>();
            var list = workOrderService.GetModel(a => true).ToList();
            var table = list.Skip(rows * (page - 1)).Take(rows).ToList();
            var pageUI = new { total = list.ToList().Count, rows = table.ToList() };
            return Json(pageUI);
        }

        public JsonResult DeleteWork(string no)
        {
            IWorkOrderService workOrderService = Container.Resolve<IWorkOrderService>();
            int id = int.Parse(no);
            try
            {
                WorkOrder workOrder = workOrderService.GetModel(a => a.WOno == id).FirstOrDefault();
                workOrderService.Delete(workOrder);
                return Json(Message.Success_Delete);
            }
            catch (Exception)
            {
                return Json(Message.Error_Delete);
            }
        }
        public ActionResult EditWork(string emaill, string title) {
            ViewData["emaill"] = emaill;
            ViewData["title"] = title;
            return View();
        }
        public JsonResult SendEmaill(string emaill,string Title, string Content) {
            MailAddress MessageFrom = new MailAddress("wufan19980120@163.com"); //发件人邮箱地址
            string MessageTo = emaill; //收件人邮箱地址
            string MessageSubject = Title; //邮件主题
            string MessageBody = Content;
            if(EmailRegister.Send(MessageFrom, MessageTo, MessageSubject, MessageBody))
                return Json("发送成功！");
           else
                return Json("发送失败！");

        }
        #endregion
    }
}
